﻿Imports System.Configuration
Imports System.IO
Imports System.Windows.Forms
'Imports DevExpress.Utils.OAuth.Provider
Imports GrapeCity.ActiveReports
Imports GrapeCity.ActiveReports.Configuration
'Imports GrapeCity.ActiveReports.ExpressionEvaluation
Imports GrapeCity.ActiveReports.PageReportModel
Imports GrapeCity.ActiveReports.Viewer.Win.Internal.Export
Imports GrapeCity.ActiveReports.PageReport
Imports GrapeCity
Imports GrapeCity.ActiveReports.Document
Imports GrapeCity.ActiveReports.Export.Excel.Page
Imports GrapeCity.ActiveReports.Export.Excel.Section
Imports GrapeCity.ActiveReports.Export.Pdf.Page
Imports GrapeCity.ActiveReports.Export.Word
Imports GrapeCity.ActiveReports.Export.Word.Page
Imports GrapeCity.ActiveReports.Export.Word.Section
Imports GrapeCity.ActiveReports.Rendering.IO

Public Class DlgReportView

#Region "窗体申明变量"

    Private _nMidDbConnection1 As String

    ''' <summary>
    ''' 说明：模块名      
    ''' </summary>
    ''' <remarks></remarks>
    Private _nModuleName As String

    ''' <summary>
    ''' 说明：字段对应模块名=f_columnlib.col_tablename      
    ''' </summary>
    ''' <remarks></remarks>
    Private _nColumnName As String

    ''' <summary>
    ''' 说明：数据库链接参数      
    ''' </summary>
    ''' <remarks></remarks>
    Private _nConnection1 As String

    Private _nMainDataSource1 As DataTable
    Private _nReportFileName1 As String
    Private _exportForm As ExportForm
    Private _reportType As System.Nullable(Of ExportForm.ReportType)
    Private _nDataSource1 As System.Data.DataSet
    ''' <summary>
    ''' 2021.5.22
    ''' 日志信息
    ''' </summary>
    Private _nStrlog As String
#End Region

#Region "窗体自定义属性"

    ''' <summary>
    ''' 2018.12.9
    ''' 中间库数据库连接
    ''' </summary>
    ''' <returns></returns>
    Public Property NMidDbConnection As String
        Get
            Return _nMidDbConnection1
        End Get
        Set
            _nMidDbConnection1 = Value
        End Set
    End Property

    ''' <summary>
    ''' 说明：模块名     
    ''' </summary>
    ''' <value></value>
    ''' <remarks></remarks>
    Public WriteOnly Property NModuleName As String 
        Set(value As String)
            _nModuleName = value
        End Set
    End Property

    ''' <summary>
    ''' 说明：字段模块名=f_columnlib.col_tablename       
    ''' </summary>
    ''' <value></value>
    ''' <remarks></remarks>
    Public WriteOnly Property NColumnName As String 
        Set(value As String)
            _nColumnName = value
        End Set
    End Property

    ''' <summary>
    ''' 说明：数据库链接字符串     
    ''' </summary>
    ''' <value></value>
    ''' <remarks></remarks>
    Public WriteOnly Property NConnection As String 
        Set(value As String)
            _nConnection1 = value
        End Set
    End Property
    ''' <summary>
    ''' 2019.7.4
    ''' Main主查询数据源信息
    ''' </summary>
    Public WriteOnly Property NMainDataSource As DataTable
        Set
            _nMainDataSource1 = Value
        End Set
    End Property
    ''' <summary>
    ''' 2019.10.20
    ''' 数据记录集dataset，默认包含(master,detail)等datatable
    ''' </summary>
    Public WriteOnly Property NDataSource As System.Data.DataSet
        Set
            _nDataSource1 = Value
        End Set
    End Property

    ''' <summary>
    ''' 2019.7.4
    ''' 报表文件，多数来自本地文件
    ''' </summary>
    Public WriteOnly Property NReportFileName As String
        Set
            _nReportFileName1 = Value
        End Set
    End Property

#End Region

#Region "窗体自定义函数及事件"

    Private Function P_ExportExcel(ByVal vFileName As String) As Integer
        Dim intsuc As Integer = -2
        Try

        Catch ex As Exception
            MsgBox(ex.Message, , "错误")
        End Try
        Return intsuc
    End Function

    Private Function DetermineOpenedReportType() As ExportForm.ReportType
        If ReportView.Document IsNot Nothing Then
            Return ExportForm.ReportType.Section
        End If
'        If ReportView.IsFplDocumentOpened() Then
'            Return ExportForm.ReportType.PageFpl
'        End If
        If ReportView.OpenedReport Then
            Return ExportForm.ReportType.PageCpl
        End If
        Return ExportForm.ReportType.PageCpl
    End Function

    ''' <summary>
    ''' 2019.7.4
    ''' 数据源加载程序
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="args"></param>
    Private Sub OnLocateDataSource(ByVal sender As Object, ByVal args As GrapeCity.ActiveReports.LocateDataSourceEventArgs)

        If _nDataSource1.Tables.Count = 1 Then
            If LCase(Convert.ToString(args.Dataset.Name)) = "master" Then
                args.Data = _nDataSource1.Tables(0)
            End If
            If LCase(Convert.ToString(args.DataSet.Name)) = "detail" Then
                args.Data = _nDataSource1.Tables(1)
            End If
        ElseIf _nDataSource1.Tables.Count = 2 Then
            If LCase(Convert.ToString(args.DataSet.Name)) = "master" Then
                args.Data = _nDataSource1.Tables(0)
            End If
            If LCase(Convert.ToString(args.DataSet.Name)) = "detail" Then 'Detail
                args.Data = _nDataSource1.Tables(1)
            End If
        ElseIf _nDataSource1.Tables.Count = 0 Then
            args.Data = _nMainDataSource1
        End If


    End Sub
    ''' <summary>
    ''' 2019.7.4
    ''' 加载报表
    ''' </summary>
    ''' <returns></returns>
    Public Function LoadReport() As Integer
        Dim intsuc As Integer = -2
        Try
            ' Dim strFielName As String = System.Environment.CurrentDirectory + "\Report\ShippingInstructions.rdlx"
            Dim rptPath As New FileInfo(_nReportFileName1) '..\..\Report\ShippingInstructions.rdlx")
            Dim definition As New PageReport(rptPath)
            '  definition.Report.DataSources(0).ConnectionProperties.DataProvider="OLEDB"
            '   definition.Report.DataSources(0).ConnectionProperties.ConnectString = _nConnection1 '自定义数据源连接信息 2019.7.5
            AddHandler definition.Document.LocateDataSource, AddressOf OnLocateDataSource '添加动态数据源事件，进行事件加载

            ReportView.LoadDocument(definition.Document)
            intsuc = 1
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Return intsuc
    End Function


#End Region

    Private Sub Menu_File_exit_Click(sender As Object, e As EventArgs)
        Me.Close()
    End Sub

    Private Sub DlgReportView_Shown(sender As Object, e As EventArgs) Handles Me.Shown


    End Sub



    Private Sub bbi_export_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_export.ItemClick
        Try
            Dim dlgsave As New SaveFileDialog
            dlgsave.Filter = "*.xlsx|.xlsx|*.xls|.xls"
            dlgsave.FileName = ""
            If dlgsave.ShowDialog() = DialogResult.OK Then
                Application.DoEvents()
                Dim strFileName As String = dlgsave.FileName '带路径的文件名
                '设置xls 输出设置
                Dim xlsSetting As GrapeCity.ActiveReports.Export.Excel.Page.ExcelRenderingExtensionSettings = New GrapeCity.ActiveReports.Export.Excel.Page.ExcelRenderingExtensionSettings()
                If dlgsave.Filter.Contains("xlsx") = True Then
                    xlsSetting.FileFormat = GrapeCity.ActiveReports.Export.Excel.Page.FileFormat.Xlsx
                Else
                    xlsSetting.FileFormat = GrapeCity.ActiveReports.Export.Excel.Page.FileFormat.Xls
                End If
                xlsSetting.MultiSheet = False '多sheet页面输出

                Dim excelRenderingExtension As GrapeCity.ActiveReports.Export.Excel.Page.ExcelRenderingExtension = New ExcelRenderingExtension()
                Dim LocalFilePath As String = strFileName.Substring(0, strFileName.LastIndexOf("\"))
                Dim outPutDir As System.IO.DirectoryInfo = New DirectoryInfo(LocalFilePath)
                Dim filename As String = strFileName.Substring(strFileName.LastIndexOf("\") + 1)
                Dim outputProvider1 As GrapeCity.ActiveReports.Rendering.IO.FileStreamProvider = New GrapeCity.ActiveReports.Rendering.IO.FileStreamProvider(outPutDir, filename)
                outputProvider1.OverwriteOutputFile = True
                ReportView.Render(excelRenderingExtension, outputProvider1, xlsSetting.GetSettings())
                MessageBox.Show("文件已经成功导出！", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
                _nStrlog = String.Format("用户导出{0}报表", strFileName)
                MClsConfig.WriteLog(Now.ToString, "99", MUser.UserName, Me.Name, _nStrlog, "1", _nMidDbConnection1)
                Me.Dispose()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Application.DoEvents()
        End Try

        '        Try
        '            Dim dlgsave As New SaveFileDialog
        '
        '            dlgsave.Filter = "*.xlsx|.xlsx"
        '            dlgsave.FileName = ""
        '
        '            If dlgsave.ShowDialog() = DialogResult.OK Then
        '             '   Application.DoEvents()
        '                Dim xlsExport As GrapeCity.ActiveReports.Export.Excel.Section.XlsExport = New XlsExport()
        '
        '                Dim document As GrapeCity.ActiveReports.Document.SectionDocument = New SectionDocument()
        '                document = ReportView.Document
        '                
        '                xlsExport.FileFormat = FileFormat.Xlsx '删除格式
        '                xlsExport.Export(document, "d:\1.xlxs")
        '                '                Dim XlsExport1 As GrapeCity.ActiveReports.Export.Excel.Section.XlsExport = New GrapeCity.ActiveReports.Export.Excel.Section.XlsExport()
        '                '                XlsExport1.FileFormat = GrapeCity.ActiveReports.Export.Excel.Section.FileFormat.Xlsx
        '                '                XlsExport1.Export(document, dlgSave.FileName)
        '                MessageBox.Show("文件已经成功导出！", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
        '            End If
        '
        '        Catch __unusedException1__ As Exception
        '            MessageBox.Show("导出文件错误请检查相关设置！", "", MessageBoxButtons.OK, MessageBoxIcon.[Error])
        '        Finally
        '            Application.DoEvents()
        '        End Try
    End Sub

    Private Sub bbi_word_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_word.ItemClick
        Try

            Dim dlgsave As New SaveFileDialog
            dlgsave.Filter = "*.docx|.docx|*.doc|.doc"
            dlgsave.FileName = ""
            If dlgsave.ShowDialog() = DialogResult.OK Then
                Application.DoEvents()
                Dim strFileName As String = dlgsave.FileName '带路径的文件名
                '设置xls 输出设置
                Dim word As GrapeCity.ActiveReports.Export.Word.Page.Settings = New GrapeCity.ActiveReports.Export.Word.Page.Settings()
                Dim wordRenderingExtension As GrapeCity.ActiveReports.Export.Word.Page.WordRenderingExtension = New WordRenderingExtension()
                Dim LocalFilePath As String = strFileName.Substring(0, strFileName.LastIndexOf("\"))
                Dim outPutDir As System.IO.DirectoryInfo = New DirectoryInfo(LocalFilePath)
                Dim filename As String = strFileName.Substring(strFileName.LastIndexOf("\")+1)
                Dim outputProvider1 As GrapeCity.ActiveReports.Rendering.IO.FileStreamProvider = New GrapeCity.ActiveReports.Rendering.IO.FileStreamProvider(outPutDir, filename)
                outputProvider1.OverwriteOutputFile = True
                ReportView.Render(wordRenderingExtension, outputProvider1, word)
                MessageBox.Show("文件已经成功导出！", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
                _nStrlog = String.Format("用户导出{0}报表", strFileName)
                MClsConfig.WriteLog(Now.ToString, "99", MUser.UserName, Me.Name, _nStrlog, "1", _nMidDbConnection1)
                Me.Dispose()

            End If


        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub bbi_report_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_report.ItemClick
'        If _exportForm Is Nothing Then
'            Dim flag As Boolean?
'            flag = GrapeCity.ActiveReports.ReportsCore.Configuration.ConfigurationHelper.GetConfigFlag(GrapeCity.ActiveReports.ReportsCore.Configuration.ConfigurationHelper.UsePdfExportFilterKey)
'            _exportForm = New ExportForm(flag.HasValue AndAlso flag.Value = True)
'        End If
'
'        Dim reportType = If(_reportType, DetermineOpenedReportType())
'        _exportForm.Show(Me, New ExportViewer(ReportView), reportType)
    End Sub

    Private Sub bbi_pdf_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_pdf.ItemClick
        Try

            Dim dlgsave As New SaveFileDialog
            dlgsave.Filter = "*.pdf|.pdf"
            dlgsave.FileName = ""
            If dlgsave.ShowDialog() = DialogResult.OK Then
                Application.DoEvents()
                Dim strFileName As String = dlgsave.FileName '带路径的文件名
                '输出设置
                Dim pdfSetting As GrapeCity.ActiveReports.Export.Pdf.Page.Settings  =New GrapeCity.ActiveReports.Export.Pdf.Page.Settings()
                pdfSetting.DisplayMode = DisplayMode.FullScreen
                pdfSetting.Author = "admin"
                Dim RenderingExtension As GrapeCity.ActiveReports.Export.Pdf.Page.PdfRenderingExtension = New PdfRenderingExtension()
                Dim LocalFilePath As String = strFileName.Substring(0, strFileName.LastIndexOf("\"))
                Dim outPutDir As System.IO.DirectoryInfo = New DirectoryInfo(LocalFilePath)
                Dim filename As String = strFileName.Substring(strFileName.LastIndexOf("\") + 1)
                Dim outputProvider As GrapeCity.ActiveReports.Rendering.IO.FileStreamProvider = New GrapeCity.ActiveReports.Rendering.IO.FileStreamProvider(outPutDir, filename)
                outputProvider.OverwriteOutputFile = True
                ReportView.Render(RenderingExtension, outputProvider, pdfSetting)
                _nStrlog = String.Format("用户导出{0}报表", strFileName)
                MClsConfig.WriteLog(Now.ToString, "99", MUser.UserName, Me.Name, _nStrlog, "1", _nMidDbConnection1)
                Me.Dispose()

            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub bbi_exit_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exit.ItemClick
        Me.Dispose()
    End Sub

    '    Private Sub bbi_report_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_report.ItemClick
    '        If _exportForm Is Nothing Then
    '            Dim flag As Boolean?
    '            flag = GrapeCity.ActiveReports.ReportsCore.Configuration.ConfigurationHelper.GetConfigFlag(GrapeCity.ActiveReports.ReportsCore.Configuration.ConfigurationHelper.UsePdfExportFilterKey)
    '            _exportForm = New ExportForm(flag.HasValue AndAlso flag.Value = True)
    '        End If
    '
    '        Dim reportType = If(_reportType, DetermineOpenedReportType())
    '        _exportForm.Show(Me, New ExportViewer(ReportView), reportType)
    '    End Sub
End Class